﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class TLHoaDon : System.Web.UI.Page
{
    SqlParameter[] p;
    clsXuLy ex = new clsXuLy();
    string frmName = "frmTLHoaDon";
    static int f_SuDung = 0, f_Them = 0, f_Sua = 0, f_Xoa = 0, f_XemTatCa = 0, f_InBaoCao = 0;
    public string Header = System.Configuration.ConfigurationSettings.AppSettings["Header"].ToString();
    static DataTable dt;
    static int PageNumber = 5;
    static int CurrentPage = 1;
    double tongphaitravat;
    double tongphaitrakhongvat;
    int pc;
    int loaicongno;
    float sotien;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Convert.ToString(Session["user"])))
            gstGetMess("Hết phiên làm việc, vui lòng đăng nhập để tiếp tục", "Default.aspx");
        else
        {
            if (!IsPostBack)
            {

                btnCancel_Click(sender, e);

                Title = "Thiết lập hóa đơn | " + Header;

                string idnguoidung = Session["IDUser"].ToString();
                string sql = "select SuDung,Them,Sua,Xoa,InBaoCao,XemTatCa from XDAPhanQuyen where IDnguoidung='" + idnguoidung + "' and tag='" + frmName + "'";

                DataTable dt2 = ex.GetData_Text(sql);
                if (dt2.Rows.Count > 0)
                {
                    f_SuDung = int.Parse(dt2.Rows[0]["SuDung"].ToString());
                    f_Them = int.Parse(dt2.Rows[0]["Them"].ToString());
                    f_Sua = int.Parse(dt2.Rows[0]["Sua"].ToString());
                    f_Xoa = int.Parse(dt2.Rows[0]["Xoa"].ToString());
                    f_InBaoCao = int.Parse(dt2.Rows[0]["InBaoCao"].ToString());
                    f_XemTatCa = int.Parse(dt2.Rows[0]["XemTatCa"].ToString());
                }
                if (f_SuDung.Equals(1))
                {
                    btnCancel_Click(sender, e);

                    for (int i = 1; i <= 12; i++)
                    {
                        dlThang.Items.Add(new ListItem("Tháng " + i.ToString(), i.ToString()));
                    }
                    dlThang.Items.Insert(0, new ListItem("Theo thời gian", ""));
                    dlThang.SelectedIndex = 0;

                    int year1 = DateTime.Now.Year - 3;
                    int year2 = DateTime.Now.Year;
                    for (int i = year2; i >= year1; i--)
                    {
                        dlNam.Items.Add(new ListItem("Năm " + i.ToString(), i.ToString()));
                        drnam.Items.Add(new ListItem("Năm " + i.ToString(), i.ToString()));
                    }
                    dlNam.SelectedValue = year2.ToString();
                    drnam.SelectedValue = year2.ToString();
                    txtTuNgay.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    txtDenNgay.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    dlNam.Visible = false;
                    LoadNCC();
                    GV.DataSource = ex.GetData("sp_ThietLapHoaDon_ListThanhTienHang");
                    GV.DataBind();
                }
                else
                    gstGetMess("Bạn không có quyền xem trang này", "Home.aspx");

            }
        }
    }
    void LoadNCCTK()
    {
        dlnhacungcap.Items.Clear();
        dlnhacungcap.DataSource = ex.GetData("sp_ThietLapHoaDon_ListThanhTienHang_ListNhanVien");
        dlnhacungcap.DataBind();
        dlnhacungcap.Items.Insert(0, new ListItem("--Chọn bên thanh toán--", ""));
        dlnhacungcap.SelectedIndex = 0;
    }

   
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        LoadNhaCungCap();
        LoadDonVi();
        FirstGridViewRow();
        
       
        GridView1.DataSource = ex.GetData("sp_ThietLapHoaDon_List");
        GridView1.DataBind();
        txtngaythang.Text = "";
        drnhacungcap.SelectedIndex = 0;
        txtthanhtienhang.Text = "";
        txtthanhtienhoadon.Text = "";
        txtkhachvanglai.Enabled = true;
        txtphantramthue.Text = "";
        txtsohd.Text = "";
        txtmasothue.Text = "";
        txtchenhlech.Text = "";
        btncapnhat.Visible = false;
        btnSave.Visible = true;
        txtkhachvanglai.Text = "";
        ckChenhlech.Checked = false;
        LoadNCCTK();
        ckChenhlech.Visible = true;
        HiddenField1.Value = "";
        hdID.Value = "";
    }

    public void LoadNCC()
    {
        getDate();
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@TuNgay", ex.GetNgayThang(hdTuNgay.Value));
        p[0].SqlDbType = SqlDbType.SmallDateTime;
        p[1] = new SqlParameter("@DenNgay", ex.GetNgayThang(hdDenNgay.Value));
        p[1].SqlDbType = SqlDbType.SmallDateTime;
        DropDownList3.Items.Clear();
        DropDownList3.DataSource = ex.GetData("sp_ThietLapHoaDon_List_NCC", p);
        DropDownList3.DataBind();
        DropDownList3.Items.Insert(0, new ListItem("--Chọn khách hàng--", ""));
        DropDownList3.SelectedIndex = 0;
    }

    public void getDate()
    {
        if (dlThang.SelectedIndex.Equals(0))
        {
            hdTuNgay.Value = txtTuNgay.Text;
            hdDenNgay.Value = txtDenNgay.Text;
        }
        else
        {
            txtTuNgay.Text = "1/" + dlThang.SelectedValue + "/" + dlNam.SelectedValue;
            txtDenNgay.Text = GetLastDayOfMonth(int.Parse(dlThang.SelectedValue)).ToString("dd/MM/yyyy");
            hdTuNgay.Value = txtTuNgay.Text;
            hdDenNgay.Value = txtDenNgay.Text;
        }
    }
    public DateTime GetLastDayOfMonth(int iMonth)
    {
        DateTime dtResult = new DateTime(int.Parse(dlNam.SelectedValue), iMonth, 1);
        dtResult = dtResult.AddMonths(1);
        dtResult = dtResult.AddDays(-(dtResult.Day));
        return dtResult;
    }
    private void gstGetMess(string gstMess, string gstLink)
    {
        if (gstLink == "")
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "')", true);
        else
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "');window.location.href='" + gstLink + "'", true);

    }
    void LoadNhaCungCap()
    {
        drnhacungcap.Items.Clear();
        drnhacungcap.DataSource = ex.GetData("sp_ThietLapHoaDon_ListThanhTienHang_ListNhanVien");
        drnhacungcap.DataBind();
        drnhacungcap.Items.Insert(0, new ListItem("--Chọn nhà cung cấp--", ""));
        drnhacungcap.SelectedIndex = 0;
    }
    void LoadDonVi()
    {
        drdonvi.Items.Clear();
        drdonvi.DataSource = ex.GetData("sp_xdathietlaphoadon_ListDonVi");
        drdonvi.DataBind();
        drdonvi.Items.Insert(0, new ListItem("--Chọn đơn vị--", ""));
        drdonvi.SelectedIndex = 0;
    }

    protected void drnhacungcap_SelectedIndexChanged(object sender, EventArgs e)
    {
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@ngaythang", ex.GetNgayThang(txtngaythang.Text.Trim()));
        p[0].SqlDbType = SqlDbType.SmallDateTime;
        p[1] = new SqlParameter("@NhaCungCap", ex.GetGuid(drnhacungcap.SelectedValue));
        p[1].SqlDbType = SqlDbType.UniqueIdentifier;

        dt = ex.GetData("sp_xdathietlaphoadon_ListThanhTienHang", p);
        if (dt.Rows.Count > 0)
        {
            txtthanhtienhang.Text = ConvertDecimal(double.Parse(dt.Rows[0]["tienhang"].ToString()));

        }
        else
        {
            txtthanhtienhang.Text = "0";

        }
    }
    string ConvertDecimal(double s)
    {
        string q = "";
        if (s.ToString().Contains("."))
        {
            double x = double.Parse(s.ToString().Substring(0, s.ToString().IndexOf('.')));
            q = (x != 0 && x > 999) ? string.Format("{0:0,0}", x) : x.ToString();
            q += s.ToString().Substring(s.ToString().IndexOf('.'));
        }
        else
            q = (s != 0 && s > 999) ? string.Format("{0:0,0}", s) : s.ToString();
        return q;
    }
    protected void txtngaythang_TextChanged(object sender, EventArgs e)
    {
        drnhacungcap_SelectedIndexChanged(sender, e);
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (f_Them.Equals(1))
        {
            Guid idhoadon = Guid.NewGuid();
            try
            {

                p = new SqlParameter[17];
                p[0] = new SqlParameter("@IDs", idhoadon);
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                p[1] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text));
                p[1].SqlDbType = SqlDbType.SmallDateTime;
                p[2] = new SqlParameter("@BenNhanTien", ex.GetGuid(drnhacungcap.SelectedValue));
                p[2].SqlDbType = SqlDbType.UniqueIdentifier;
                p[3] = new SqlParameter("@ThanhTienHang", double.Parse(txtthanhtienhang.Text.Trim().Equals("") ? "0" : txtthanhtienhang.Text.Trim()));
                p[3].SqlDbType = SqlDbType.Float;
                p[4] = new SqlParameter("@ThanhTienHoaDon", double.Parse(txtthanhtienhoadon.Text.Trim().Equals("") ? "0" : txtthanhtienhoadon.Text.Trim()));
                p[4].SqlDbType = SqlDbType.Float;
                p[5] = new SqlParameter("@PhanTramThue", double.Parse(txtphantramthue.Text.Trim().Equals("") ? "0" : txtphantramthue.Text.Trim()));
                p[5].SqlDbType = SqlDbType.Float;
                p[6] = new SqlParameter("@SoHD", txtsohd.Text.Trim());
                p[6].SqlDbType = SqlDbType.VarChar;
                p[7] = new SqlParameter("@MaSoThue", txtmasothue.Text.Trim());
                p[7].SqlDbType = SqlDbType.VarChar;
                p[8] = new SqlParameter("@ChenhLechTra", double.Parse(txtchenhlech.Text.Trim().Equals("") ? "0" : txtchenhlech.Text.Trim()));
                p[8].SqlDbType = SqlDbType.Float;
                p[9] = new SqlParameter("@DaTraChenhLech", ckChenhlech.Checked ? 1 : 2);
                p[9].SqlDbType = SqlDbType.Int;

                p[10] = new SqlParameter("@NgayTao", DateTime.Now);
                p[10].SqlDbType = SqlDbType.SmallDateTime;
                p[11] = new SqlParameter("@NguoiTao", Session["user"].ToString());
                p[11].SqlDbType = SqlDbType.NVarChar;
                p[12] = new SqlParameter("@Del", 1);
                p[12].SqlDbType = SqlDbType.Int;
                p[13] = new SqlParameter("@LoaiHoanDon", 2);
                p[13].SqlDbType = SqlDbType.Int;
                p[14] = new SqlParameter("@KhachVangLai", txtkhachvanglai.Text.Trim());
                p[14].SqlDbType = SqlDbType.NVarChar;
                p[15] = new SqlParameter("@Thang", int.Parse(hdID.Value.Equals("") ? "0" : hdID.Value));
                p[15].SqlDbType = SqlDbType.Int;
                p[16] = new SqlParameter("@Nam", int.Parse(HiddenField1.Value.Equals("") ? "0" : HiddenField1.Value));
                p[16].SqlDbType = SqlDbType.Int;
                ex.ExecuteNonQuerry("sp_xdathietlaphoadon_Add", p);
                for (int i = 0; i < GV1.Rows.Count; i++)
                {
                    TextBox txtTen = (TextBox)GV1.Rows[i].Cells[1].FindControl("txtnoidung");

                    p = new SqlParameter[4];
                    p[0] = new SqlParameter("@IDs", Guid.NewGuid());
                    p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[1] = new SqlParameter("@NoiDung", txtTen.Text.Trim());
                    p[1].SqlDbType = SqlDbType.NVarChar;
                    p[2] = new SqlParameter("@IDHoaDon", idhoadon);
                    p[2].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[3] = new SqlParameter("@Del", 1);
                    p[3].SqlDbType = SqlDbType.Int;

                    ex.ExecuteNonQuerry("sp_XDANoiDungHoaDon_Add", p);
                }
                if (ckChenhlech.Checked)
                {
                    p = new SqlParameter[1];
                    p[0] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text.Trim()));
                    p[0].SqlDbType = SqlDbType.SmallDateTime;
                    dt = ex.GetData("sp_xdagetsophieuchiconnotravat_TienMat", p);
                    int sopc = Int16.Parse(dt.Rows[0]["sopc"].ToString());
                    if (sopc == 0)
                        pc = 1;
                    else pc = sopc + 1;
                    p = new SqlParameter[11];
                    p[0] = new SqlParameter("@IDs", Guid.NewGuid());
                    p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[1] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text.Trim()));
                    p[1].SqlDbType = SqlDbType.SmallDateTime;
                    p[2] = new SqlParameter("@NoiDung", "Thanh toán tiền chênh lệch hóa đơn ");
                    p[2].SqlDbType = SqlDbType.NVarChar;
                    p[3] = new SqlParameter("@DonVi", ex.GetGuid(drnhacungcap.SelectedValue));
                    p[3].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[4] = new SqlParameter("@SoPC", pc);
                    p[4].SqlDbType = SqlDbType.Int;
                    p[5] = new SqlParameter("@TaiKhoan", DBNull.Value);
                    p[5].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[6] = new SqlParameter("@Del", 1);
                    p[6].SqlDbType = SqlDbType.Int;
                    p[7] = new SqlParameter("@LoaiCongNo", 2);
                    p[7].SqlDbType = SqlDbType.Int;
                    p[8] = new SqlParameter("@SoTien", double.Parse(txtchenhlech.Text.Trim().Equals("") ? "0" : txtchenhlech.Text.Trim()));
                    p[8].SqlDbType = SqlDbType.Float;
                    p[9] = new SqlParameter("@IDLenhChi", idhoadon);
                    p[9].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[10] = new SqlParameter("@NhanVien", DBNull.Value);
                    p[10].SqlDbType = SqlDbType.UniqueIdentifier;
                    ex.ExecuteNonQuerry("sp_xdaphieuchicongno_Add", p);
                }

                gstGetMess("Thêm thành công", "");
                btnCancel_Click(sender, e);

            }
            catch (Exception a)
            {
                gstGetMess("Có lỗi trong quá trình lưu, xem trong file log", "");
                ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tthiết lập hóa đơn\t" + a.Message);
            }
        }
        else
            gstGetMess("Bạn không có quyền thêm dữ liệu trên trang này", "");
    }
    protected void ckCohoadon_CheckedChanged(object sender, EventArgs e)
    {

        //ckCohoadon.Checked = true;
        //txtthanhtienhoadon.Enabled = true;

        //txtphantramthue.Enabled = true;
        //txtsohd.Enabled = true;
        //txtmasothue.Enabled = true;
        //txtchenhlech.Enabled = true;
        //txtngaythang.Enabled = true;

    }
    protected void btnXem_Click(object sender, EventArgs e)
    {
        if (dlnhacungcap.SelectedIndex == 0)
        {
            p = new SqlParameter[2];
            p[0] = new SqlParameter("@Thang", int.Parse(drthang.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(drnam.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;

            GV.DataSource = ex.GetData("sp_ThietLapHoaDon_TKTheoThoiGian", p);
            GV.DataBind();

        }
        else
        {
            p = new SqlParameter[3];
            p[0] = new SqlParameter("@Thang", int.Parse(drthang.SelectedValue));
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@Nam", int.Parse(drnam.SelectedValue));
            p[1].SqlDbType = SqlDbType.Int;
            p[2] = new SqlParameter("@NCC", ex.GetGuid(dlnhacungcap.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            GV.DataSource = ex.GetData("sp_ThietLapHoaDon_TKTheoThoiGian_NCC", p);
            GV.DataBind();

        }

    }
    protected void GV_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GV.SelectedRow;
        this.txtthanhtienhang.Text = row.Cells[6].Text;
        this.hdID.Value = row.Cells[1].Text;
        this.HiddenField1.Value = row.Cells[2].Text;
        Label lbTag = (Label)row.Cells[5].FindControl("lbTag");
        this.drnhacungcap.SelectedValue = lbTag.Text;

        txtthanhtienhoadon.Enabled = true;

        txtphantramthue.Enabled = true;
        txtsohd.Enabled = true;
        txtmasothue.Enabled = true;
        txtchenhlech.Enabled = true;
        txtngaythang.Enabled = true;
        txtkhachvanglai.Enabled = false;
    }


    private void AddNewRow()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox txtnoidung = (TextBox)GV1.Rows[rowIndex].Cells[1].FindControl("txtnoidung");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["Noidung"] = txtnoidung.Text.Trim();

                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                GV1.DataSource = dtCurrentTable;
                GV1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousData();

    }
    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox txtnoidung = (TextBox)GV1.Rows[rowIndex].Cells[1].FindControl("txtnoidung");

                    GV1.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    txtnoidung.Focus();
                    txtnoidung.Text = dt.Rows[i]["Noidung"].ToString();



                    rowIndex++;
                }
            }
        }
    }
    private void FirstGridViewRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Noidung", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Noidung"] = string.Empty;

        dt.Rows.Add(dr);

        ViewState["CurrentTable"] = dt;


        GV1.DataSource = dt;
        GV1.DataBind();
    }
    protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SetRowData();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["CurrentTable"] = dt;
                GV1.DataSource = dt;
                GV1.DataBind();

                for (int i = 0; i < GV1.Rows.Count - 1; i++)
                {
                    GV1.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                SetPreviousData();
            }
        }
    }
    private void SetRowData()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox txtnoidung = (TextBox)GV1.Rows[rowIndex].Cells[1].FindControl("txtnoidung");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["Noidung"] = txtnoidung.Text.Trim();

                    rowIndex++;
                }

                ViewState["CurrentTable"] = dtCurrentTable;
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        AddNewRow();
    }
    public static void MergeRows(GridView gridView)
    {
        for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        {
            GridViewRow row = gridView.Rows[rowIndex];
            GridViewRow previousRow = gridView.Rows[rowIndex + 1];

            for (int i = 2; i < row.Cells.Count; i++)
            {
                if (row.Cells[i].Text.Equals(previousRow.Cells[i].Text))
                {
                    row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 : previousRow.Cells[i].RowSpan + 1;
                    previousRow.Cells[i].Visible = false;
                }
            }
        }
    }
    protected void GridView1_PreRender(object sender, EventArgs e)
    {
        MergeRows(GridView1);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (DropDownList3.SelectedIndex == 0)
        {
            p = new SqlParameter[2];
            p[0] = new SqlParameter("@TuNgay", ex.GetNgayThang(hdTuNgay.Value));
            p[0].SqlDbType = SqlDbType.SmallDateTime;
            p[1] = new SqlParameter("@DenNgay", ex.GetNgayThang(hdDenNgay.Value));
            p[1].SqlDbType = SqlDbType.SmallDateTime;
            GridView1.DataSource = ex.GetData("sp_ThietLapHoaDon_List_TheoThoiGian_DauVao", p);
            GridView1.DataBind();

        }
        else
        {
            p = new SqlParameter[3];
            p[0] = new SqlParameter("@TuNgay", ex.GetNgayThang(hdTuNgay.Value));
            p[0].SqlDbType = SqlDbType.SmallDateTime;
            p[1] = new SqlParameter("@DenNgay", ex.GetNgayThang(hdDenNgay.Value));
            p[1].SqlDbType = SqlDbType.SmallDateTime;
            p[2] = new SqlParameter("@NCC", DropDownList3.SelectedValue);
            p[2].SqlDbType = SqlDbType.NVarChar;
            GridView1.DataSource = ex.GetData("sp_ThietLapHoaDon_List_TheoThoiGian_DauVao_NCC", p);
            GridView1.DataBind();

        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string ID = e.CommandArgument.ToString();
        HiddenField1.Value = ID;
        Guid gID = new Guid(ID);
        if (e.CommandName.Equals("Del"))
        {
            p = new SqlParameter[1];
            p[0] = new SqlParameter("@IDs", gID);
            p[0].SqlDbType = SqlDbType.UniqueIdentifier;
            ex.ExecuteNonQuerry("sp_xdathietlaphoadon_Del", p);


            p = new SqlParameter[1];
            p[0] = new SqlParameter("@IDs", gID);
            p[0].SqlDbType = SqlDbType.UniqueIdentifier;
            ex.ExecuteNonQuerry("sp_xdanoidunghoadon_DelNoiDung", p);
            p = new SqlParameter[1];
            p[0] = new SqlParameter("@IDs", gID);
            p[0].SqlDbType = SqlDbType.UniqueIdentifier;
            ex.ExecuteNonQuerry("sp_xdaphieuchicongno_Del", p);
            gstGetMess("Xóa thành công", "");
            btnCancel_Click(sender, e);
        }
        else
            if (e.CommandName.Equals("Select"))
            {
               
                p = new SqlParameter[1];
                p[0] = new SqlParameter("@IDs", gID);
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                DataTable dt = ex.GetData("sp_xdathietlaphoadon_ListById", p);
                if (dt.Rows.Count > 0)
                {
                    try
                    {
                        txtngaythang.Text = dt.Rows[0]["ngaythang"].ToString();
                        drnhacungcap.SelectedValue = dt.Rows[0]["bennhantien"].ToString();
                        txtthanhtienhang.Text = dt.Rows[0]["thanhtienhang"].ToString();
                        txtthanhtienhoadon.Text = dt.Rows[0]["thanhtienhoadon"].ToString();
                        txtphantramthue.Text = dt.Rows[0]["phantramthue"].ToString();
                        txtsohd.Text = dt.Rows[0]["sohd"].ToString();
                        txtmasothue.Text = dt.Rows[0]["masothue"].ToString();
                        txtchenhlech.Text = dt.Rows[0]["chenhlechtra"].ToString();
                        txtkhachvanglai.Text = dt.Rows[0]["khachvanglai"].ToString();
                        string datra;
                        datra = dt.Rows[0]["datrachenhlech"].ToString();
                        hdID.Value = datra;
                        if (datra.Equals("1"))
                            ckChenhlech.Checked = true;
                        else
                            ckChenhlech.Checked = false;
                        txtthanhtienhoadon.Enabled = true;

                        txtphantramthue.Enabled = true;
                        txtsohd.Enabled = true;
                        txtmasothue.Enabled = true;
                        txtchenhlech.Enabled = true;
                        txtngaythang.Enabled = true;
                    }
                    catch (Exception ax)
                    {
                        gstGetMess("Có lỗi trong quá trình xem, xem trong file log", "");
                        ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tSố dư tiền mặt\t" + ax.Message);
                    }

                }

                int rowIndex = 0;
                p = new SqlParameter[1];
                p[0] = new SqlParameter("@IDs", gID);
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                dt = ex.GetData("sp_xdanoidunghoadon", p);
                if (ViewState["CurrentTable"] != null)
                {

                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            TextBox txtnoidung = (TextBox)GV1.Rows[rowIndex].Cells[1].FindControl("txtnoidung");

                            GV1.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                            txtnoidung.Focus();
                            txtnoidung.Text = dt.Rows[i]["noidung"].ToString();

                            rowIndex++;
                            if (txtnoidung.Text != null)
                            {
                                AddNewRow();
                            }
                        }
                    }

                }

                else
                {
                    Response.Write("ViewState is null");
                }


                btncapnhat.Visible = true;
                btnSave.Visible = false;
            }

    }
    protected void btncapnhat_Click(object sender, EventArgs e)
    {
        int datra;
        if (f_Sua.Equals(1))
        {
            try
            {
                Guid gID = new Guid(HiddenField1.Value);
                datra = Int16.Parse(hdID.Value);

                p = new SqlParameter[1];
                p[0] = new SqlParameter("@IDs", gID);
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                ex.ExecuteNonQuerry("sp_xdanoidunghoadon_DelNoiDung", p);

                for (int i = 0; i < GV1.Rows.Count; i++)
                {
                    TextBox txtTen = (TextBox)GV1.Rows[i].Cells[1].FindControl("txtnoidung");
                    if (txtTen.Text != "")
                    {
                        p = new SqlParameter[4];
                        p[0] = new SqlParameter("@IDs", Guid.NewGuid());
                        p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                        p[1] = new SqlParameter("@NoiDung", txtTen.Text.Trim());
                        p[1].SqlDbType = SqlDbType.NVarChar;
                        p[2] = new SqlParameter("@IDHoaDon", gID);
                        p[2].SqlDbType = SqlDbType.UniqueIdentifier;
                        p[3] = new SqlParameter("@Del", 1);
                        p[3].SqlDbType = SqlDbType.Int;
                        ex.ExecuteNonQuerry("sp_XDANoiDungHoaDon_Add", p);
                    }


                }

                if (datra == 1 && ckChenhlech.Checked == true)
                {


                    p = new SqlParameter[6];

                    p[0] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text.Trim()));
                    p[0].SqlDbType = SqlDbType.SmallDateTime;
                    p[1] = new SqlParameter("@NoiDung", "Thanh toán tiền chênh hóa đơn");
                    p[1].SqlDbType = SqlDbType.NVarChar;
                    p[2] = new SqlParameter("@TaiKhoan", DBNull.Value);
                    p[2].SqlDbType = SqlDbType.UniqueIdentifier;

                    p[3] = new SqlParameter("@SoTien", double.Parse(txtchenhlech.Text.Trim().Replace(",", "").Equals("") ? "0" : txtchenhlech.Text.Trim().Replace(",", "")));
                    p[3].SqlDbType = SqlDbType.Float;
                    p[4] = new SqlParameter("@IDLenhChi", gID);
                    p[4].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[5] = new SqlParameter("@NhanVien", DBNull.Value);
                    p[5].SqlDbType = SqlDbType.UniqueIdentifier;
                    ex.ExecuteNonQuerry("sp_ThanhToanCongNo_UpdatePhieuChiCongNo", p);

                }
                else if (datra == 1 && ckChenhlech.Checked == false)
                {
                    p = new SqlParameter[1];
                    p[0] = new SqlParameter("@IDs", gID);
                    p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                    ex.ExecuteNonQuerry("sp_xdaphieuchicongno_Del", p);
                    gstGetMess("Xóa thành công", "");
                }
                else if (datra == 2 && ckChenhlech.Checked == true)
                {
                    p = new SqlParameter[1];
                    p[0] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text.Trim()));
                    p[0].SqlDbType = SqlDbType.SmallDateTime;
                    dt = ex.GetData("sp_xdagetsophieuchiconnotravat_TienMat", p);
                    int sopc = Int16.Parse(dt.Rows[0]["sopc"].ToString());
                    if (sopc == 0)
                        pc = 1;
                    else pc = sopc + 1;
                    p = new SqlParameter[11];
                    p[0] = new SqlParameter("@IDs", Guid.NewGuid());
                    p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[1] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text.Trim()));
                    p[1].SqlDbType = SqlDbType.SmallDateTime;
                    p[2] = new SqlParameter("@NoiDung", "Thanh toán tiền chênh lệch hóa đơn ");
                    p[2].SqlDbType = SqlDbType.NVarChar;
                    p[3] = new SqlParameter("@DonVi", ex.GetGuid(drnhacungcap.SelectedValue));
                    p[3].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[4] = new SqlParameter("@SoPC", pc);
                    p[4].SqlDbType = SqlDbType.Int;
                    p[5] = new SqlParameter("@TaiKhoan", DBNull.Value);
                    p[5].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[6] = new SqlParameter("@Del", 1);
                    p[6].SqlDbType = SqlDbType.Int;
                    p[7] = new SqlParameter("@LoaiCongNo", 2);
                    p[7].SqlDbType = SqlDbType.Int;
                    p[8] = new SqlParameter("@SoTien", double.Parse(txtchenhlech.Text.Trim().Equals("") ? "0" : txtchenhlech.Text.Trim()));
                    p[8].SqlDbType = SqlDbType.Float;
                    p[9] = new SqlParameter("@IDLenhChi", gID);
                    p[9].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[10] = new SqlParameter("@NhanVien", DBNull.Value);
                    p[10].SqlDbType = SqlDbType.UniqueIdentifier;
                    ex.ExecuteNonQuerry("sp_xdaphieuchicongno_Add", p);
                }
                p = new SqlParameter[11];
                p[0] = new SqlParameter("@IDs", gID);
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                p[1] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text));
                p[1].SqlDbType = SqlDbType.SmallDateTime;
                p[2] = new SqlParameter("@BenNhanTien", ex.GetGuid(drnhacungcap.SelectedValue));
                p[2].SqlDbType = SqlDbType.UniqueIdentifier;
                p[3] = new SqlParameter("@ThanhTienHang", double.Parse(txtthanhtienhang.Text.Trim().Equals("") ? "0" : txtthanhtienhang.Text.Trim()));
                p[3].SqlDbType = SqlDbType.Float;
                p[4] = new SqlParameter("@ThanhTienHoaDon", double.Parse(txtthanhtienhoadon.Text.Trim().Equals("") ? "0" : txtthanhtienhoadon.Text.Trim()));
                p[4].SqlDbType = SqlDbType.Float;
                p[5] = new SqlParameter("@PhanTramThue", double.Parse(txtphantramthue.Text.Trim().Equals("") ? "0" : txtphantramthue.Text.Trim()));
                p[5].SqlDbType = SqlDbType.Float;
                p[6] = new SqlParameter("@SoHD", txtsohd.Text.Trim());
                p[6].SqlDbType = SqlDbType.VarChar;
                p[7] = new SqlParameter("@MaSoThue", txtmasothue.Text.Trim());
                p[7].SqlDbType = SqlDbType.VarChar;
                p[8] = new SqlParameter("@ChenhLechTra", double.Parse(txtchenhlech.Text.Trim().Equals("") ? "0" : txtchenhlech.Text.Trim()));
                p[8].SqlDbType = SqlDbType.Float;
                p[9] = new SqlParameter("@DaTraChenhLech", ckChenhlech.Checked ? 1 : 2);
                p[9].SqlDbType = SqlDbType.Int;


                p[10] = new SqlParameter("@KhachVangLai", txtkhachvanglai.Text.Trim());
                p[10].SqlDbType = SqlDbType.NVarChar;
                ex.ExecuteNonQuerry("sp_xdathietlaphoadon_Update", p);
                btnCancel_Click(sender, e);
                gstGetMess("Cập nhật thành công", "");
            }
            catch (Exception ax)
            {
                gstGetMess("Có lỗi trong quá trình cập nhật, xem trong file log", "");
                ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tThiết lập phạt\t" + ax.Message);
            }
        }
        else
            gstGetMess("Bạn không có quyền sửa dữ liệu trên trang này", "");
    }
    protected void dlThang_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (dlThang.SelectedIndex.Equals(0))
        {
            txtTuNgay.Visible = true;
            txtDenNgay.Visible = true;
            dlNam.Visible = false;
        }
        else
        {
            txtTuNgay.Visible = false;
            txtDenNgay.Visible = false;
            dlNam.Visible = true;
        }
        LoadNCC();
    }
}